package edu.gatech.cs2340.tigershroud;
/**
 * The TodoListActivity is the main page that the user with interact with.
 * The class allows the user to add, delete, sort, view, and modify tasks. The class
 * also provides users with the ablility to view the tasks on a map
 * @author []
 * @version 9.0x, Build April 3, 2012.
 */
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class TodoListActivity extends ListActivity 
{   
	//class variables
	private TodoDataSource tds;
	private UserDataSource uds;
	private MasterControlClass mcc;
	private TextView user, type, count, total;
	private Button badd, bsearch, bfilter, blog, bmap, bclose, bshare;
	private EditText etuname;
	private RadioGroup rgroup;
	private List<Task> tlist;
	private ListView lv;
	//private ArrayAdapter<Task> customAdapter;
	private String uname, utype, num, tuname;
	private User tuser;
	private int rselect, hcount, size;
	private boolean filterstate;
	private CheckBox cfilter;
	private Task selected;
	private Dialog dialog;
	
	/**
	 * The onCreate method is a default android method that is called when the
	 * activity is first started. This onCreate method assigns passed objects to variables, 
	 * opens the database, determines the layout of
	 * the activity, and sets listeners for items within the activity.
	 * @param saveInstanceState the Bundle name value pair that represents the state of the object
	 *
	 */
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.todolist);
        
        tds = new TodoDataSource(this);
        tds.open();
        
        mcc = new MasterControlClass();
        badd = (Button) findViewById(R.id.add);
        bmap = (Button) findViewById(R.id.map);
        bsearch = (Button) findViewById(R.id.promptSearch);
        blog = (Button) findViewById(R.id.blogout);
        bfilter = (Button) findViewById(R.id.bfilter);
        bshare = (Button) findViewById(R.id.bshare);
        rgroup = (RadioGroup) findViewById(R.id.rgfilter);
        cfilter = (CheckBox) findViewById(R.id.cbfilter);
        user = (TextView) findViewById(R.id.tvuname);
        type = (TextView) findViewById(R.id.tvtype);
        total = (TextView) findViewById(R.id.tvt);
        
        uname = getIntent().getExtras().getString("uname");
        utype = getIntent().getExtras().getString("utype");
        user.setText(uname);
        type.setText(utype);
        
        hcount = checkReminder();
        if(hcount > 0)
        {
            reminder(hcount);
        }
        refresh(display());
        
        /*
		customAdapter = new CustomAdapter(this, tlist);
		setListAdapter(customAdapter);
     	*/
		
        lv = getListView();
        lv.setTextFilterEnabled(true);
                
        lv.setOnItemClickListener(new OnItemClickListener() 
        {
        	public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
        	{
        		selected = (Task) lv.getItemAtPosition(position);
        		
        		if(selected.getDescription() != null)
        		{
	        		registerForContextMenu(lv); 
	        		openContextMenu(lv);
	        		unregisterForContextMenu(lv);
        		}
            }
        });

        bshare.setOnClickListener(new View.OnClickListener() 
        {
    	   public void onClick(View v) 
    	   {
    		   dialog = new Dialog(TodoListActivity.this);
    	       dialog.setContentView(R.layout.share);
    	       dialog.setTitle("Share task list");
    	       dialog.setCancelable(true);
    	       
    	       uds = new UserDataSource(getApplicationContext());
    	       uds.open();
    	       
    	       bshare = (Button) dialog.findViewById(R.id.bshare);
    	       bclose = (Button) dialog.findViewById(R.id.bclose);
    	       
    	       etuname = (EditText) dialog.findViewById(R.id.etuname);
    	       
    	       bshare.setOnClickListener(new View.OnClickListener() 
    	       {
    	    	   public void onClick(View v) 
    	    	   {
    	    		   Log.d("TODO", "current user type: " + utype);
    	    		   Log.d("TODO", "current user: " + mcc.getUname());
    	    		   
        	    	   tuname = etuname.getText().toString();
        	    	   tuser = uds.findUser(tuname);
        	    	   
        	    	   if(tuser == null)
        	    	   {
        	    		   Toast.makeText(getApplicationContext(), 
        	        			"This user does not exist, please try again...", Toast.LENGTH_LONG).show();
        	    	   }
        	    	   else if(!tuser.getUserName().equals(uname) && !tuser.getType().equals("super") && !utype.equals("super")) 
    	    		   {
            	    	   Log.d("TODO", "target user type: " + tuser.getType());
            	    	   Log.d("TODO", "target user: " + tuser.getUserName());
            	    	   List<Task> temp = tds.getAllTaskForUser("ASC");
	    				   mcc.setUname(tuser.getUserName());
        	    		   Log.d("TODO", "before sharing user name: " + mcc.getUname());
    	    			   size = temp.size();
    	    			   if(size == 1 && temp.get(0).getDnum() != -1)
    	    			   {
	    	    			   for(int a = 0; a < size; a++)
	    	    			   {
	    	    				   tds.insertTask(temp.get(a));
	    	    				   Log.d("TODO", "sharing task -- " + temp.get(a).getTaskName());
	    	    			   }
	    	    			   mcc.setUname(uname);
	    	    			   
	    	    			   Log.d("TODO", "after sharing user name: " + mcc.getUname());
	    	    			   Toast.makeText(getApplicationContext(), 
	           	        			"Sharing completed successfully...", Toast.LENGTH_LONG).show();
    	    			   }
    	    			   else
    	    			   {
    	    				   Toast.makeText(getApplicationContext(), 
   	           	        			"Current user does not have any task to share...", Toast.LENGTH_LONG).show();
    	    			   }
    	    			   uds.close();
    	    			   dialog.dismiss();
    	    		   }
    	    		   else
    	    		   {
    	    			   Toast.makeText(getApplicationContext(), 
    	    	        			"Sharing is only allowed between distinct normal users...", Toast.LENGTH_LONG).show();
    	    		   }
    	    	   }
    	        });
    	       
    	       bclose.setOnClickListener(new View.OnClickListener() 
    	        {
    	    	   public void onClick(View v) 
    	    	   {
    	    		   uds.close();
    	    		   dialog.dismiss();
    	    	   }
    	        });
    	       dialog.show();
    	   }
        });
        
        badd.setOnClickListener(new View.OnClickListener() 
        {
    	   public void onClick(View v) 
    	   {
    		   tds.close();
    		   Intent intent = new Intent(getApplicationContext(), TaskActivity.class);
    		   intent.putExtra("date", "");
    		   intent.putExtra("time", "");
    		   intent.putExtra("dnum", "");
               startActivity(intent);
    	   }
        });
 
        bmap.setOnClickListener(new View.OnClickListener() 
        {
        	public void onClick(View v) 
        	{
        		tds.close();
	    		Intent intent = new Intent(getApplicationContext(), MapViewActivity.class);
	            startActivity(intent);
        	}
        });

	    bsearch.setOnClickListener(new View.OnClickListener() 
	    {
	    	public void onClick(View v) 
	    	{
	    		tds.close();
	    		Intent intent = new Intent(getApplicationContext(), SearchActivity.class);
	    		intent.putExtra("uname", uname);
    			intent.putExtra("utype", utype);
	            startActivity(intent);
	    	}
	    });
	    
	    blog.setOnClickListener(new View.OnClickListener() 
	    {
	    	public void onClick(View v) 
	    	{
	    		tds.close();
	    		Toast.makeText(TodoListActivity.this, "Successful logout...", Toast.LENGTH_LONG).show();
	    		finish();
	    	}
	    });
	    
	    cfilter.setOnClickListener(new View.OnClickListener() 
	    {
	    	public void onClick(View v) 
	    	{
	    		filterstate = ((CheckBox) v).isChecked() ? true : false; 
	    		if(filterstate == false)
	    		{
	    			refresh(display());
	    		}
	    	}
	    });
	    
	    bfilter.setOnClickListener(new View.OnClickListener() 
	    {
	    	public void onClick(View v) 
	    	{
	    		if(filterstate)
	    		{
		    		rselect = rgroup.getCheckedRadioButtonId();
		    		switch(rselect)
		    		{
		    			case R.id.rbcomp:
		    				tlist = tds.searchByStatus("1", "ASC", utype);
		    				Log.d("TODO", "filter by complete");
		    				break;
		    			case R.id.rbincomp:
		    				tlist = tds.searchByStatus("0", "ASC", utype);
		    				Log.d("TODO", "filter by incomplete");
		    				break;
		    			default:
		    				tlist = tds.searchByCurrentUserName("ASC");
		    				Log.d("TODO", "no filter, show all");
		    		}
		    		refresh(tlist);
	    		}
	    	}
	    });
    }
    
/**
 * Determines the behavior of the activity once it resumes
 */
    protected void onResume()
    {
    	super.onResume();
    	tds.open();
        refresh(display());
    }
    
    /**
     * Determines the behavior of the activity once it refresh. 
     * When the activity refreshes, the list displaying tasks updates.
     */
    public void refresh(List<Task> t)
    {
        count = (TextView) findViewById(R.id.tvc);
        setListAdapter(new ArrayAdapter<Task>(getApplicationContext(), android.R.layout.simple_list_item_1, t));
        //setListAdapter(new CustomAdapter(this, tlist));
        if(t.size() == 1 && t.get(0).getDnum() == -1)
        {
        		num = "0";
        }
        else
        {
        	num = t.size() + "";
        }
        count.setText(num);
        total.setText(tds.taskCount(utype));
    }
    
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) 
    {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		MenuItem status = (MenuItem) findViewById(R.id.stat);
		inflater.inflate(R.menu.listmenu, menu);
	}
    
    public boolean onContextItemSelected(MenuItem item) 
    {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        switch(item.getItemId()) 
        {
            case R.id.edit:
     		    Intent intent = new Intent(getApplicationContext(), TaskActivity.class);
     		    intent.putExtra("date", "");
     		    intent.putExtra("time", "");
     		    intent.putExtra("dnum", "");
     		    intent.putExtra("task", selected);

     		    startActivity(intent);
                return true;
            case R.id.delete:
                tds.open();
                tds.deleteTask(selected);
                refresh(display());
                return true;
            case R.id.view:
            	Intent j = new Intent(TodoListActivity.this, TaskViewActivity.class);
        		j.putExtra("clickedTask", selected);
        		startActivity(j);
                return true;
            case R.id.stat:
            	if(selected.getStatus().equals("1"))
            	{
            		selected.setStatus("0");
            		tds.edit(selected, TodoSQLiteHelper.COLUMN_STAT, "0");
            	}
            	else 
            	{
            		selected.setStatus("1");
            		tds.edit(selected, TodoSQLiteHelper.COLUMN_STAT, "1");
            	}
            	refresh(display());
                return true;
            default:
                return super.onContextItemSelected(item);
        }
    }
    
    public List<Task> display()
    {
		if(utype.equals("super"))
		{
			return tds.getAllTask("ASC");
		}
		return tds.getAllTaskForUser("ASC");
    }
    
    public void reminder(int c)
    {	
    	dialog = new Dialog(TodoListActivity.this);
        dialog.setContentView(R.layout.reminder);
        dialog.setTitle("Critical Task Reminder");
        dialog.setCancelable(true);

        bclose = (Button) dialog.findViewById(R.id.bclose);
        count = (TextView) dialog.findViewById(R.id.tvcount);
        count.setText(c + "");
        refresh(display());

        bclose.setOnClickListener(new View.OnClickListener() 
        {
        	public void onClick(View v) 
        	{
        		dialog.dismiss();
        	}
        });
        
        dialog.show();
    }
    
    public int checkReminder()
    {
    	tlist = tds.getAllHigh(utype, "ASC");
    	int size = tlist.size();
        if(size == 1 && tlist.get(0).getDnum() == -1)
        {
        	return 0;
        }
        return size;
    }
    
    public boolean validateUsername(String uname)
    {
    	return emptyInputValidation(uname, "a username");
    }
    
    public boolean emptyInputValidation(String d, String e)
    {
    	if(d.equals(""))
    	{
    		Toast.makeText(getApplicationContext(), 
        			"Please enter " + e + "...", Toast.LENGTH_LONG).show();
    		return false;
    	}
    	return true;
    }
}


